package com.thuanhoang.boo;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONObject;

import util.BooPreference;
import util.Constant;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.boo.service.AccountService;
import com.boo.service.SendDataService;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.thuanhoang.boo.model.ObjUser;
import com.thuanhoang.boo.model.manage.ObjUserMng;

public class UpdateInfoActivity extends Activity {
	public static final String USER_UPDATE = "user.update";
	static final int DATE_DIALOG_ID = 0;
	boolean isAutoRegistering = false;

	EditText edtUserName, edtPhone, edtEmail, edtAddress, edtBirthday;
	TextView tvUserName, tvPhone, tvEmail, tvAddress, tvBirthday;
	Button btnUpdate;
	RadioGroup radioGender;
	RadioButton radioMale, radioFamale;
	View loading;

	public int yearSelected, monthSelected, daySelected;
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			yearSelected = year;
			monthSelected = monthOfYear + 1;
			daySelected = dayOfMonth;
			edtBirthday.setText(daySelected + "/" + monthSelected + "/"
					+ yearSelected);
		}
	};

	BroadcastReceiver receiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context,
				android.content.Intent intent) {
			isAutoRegistering = false;
			String userId = intent.getStringExtra("userId");
			if (userId.equals("")) {
				// show dialog confirm
				Builder build = new Builder(UpdateInfoActivity.this)
						.setCancelable(true)
						.setTitle("Autoregister")
						.setMessage(
								"This device is can not Autoregister to Server")
						.setNegativeButton("Close", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				build.create().show();
			} else {
				updateUser(false);
			}
			loading.setVisibility(View.GONE);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_account_update);
		findViewById();

		edtBirthday.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				showDialog(DATE_DIALOG_ID);

				return false;
			}
		});

		registerReceiver(receiver, new IntentFilter(USER_UPDATE));

		refreshDataContext();
		
		setEditInfo(false);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	public void findViewById() {
		edtUserName = (EditText) findViewById(R.id.edt_username);
		edtPhone = (EditText) findViewById(R.id.edt_phone);
		edtEmail = (EditText) findViewById(R.id.edt_email);
		edtAddress = (EditText) findViewById(R.id.edt_address);
		edtBirthday = (EditText) findViewById(R.id.edt_birthday);

		tvUserName = (TextView) findViewById(R.id.tv_username);
		tvPhone = (TextView) findViewById(R.id.tv_phone);
		tvEmail = (TextView) findViewById(R.id.tv_email);
		tvAddress = (TextView) findViewById(R.id.tv_address);
		tvBirthday = (TextView) findViewById(R.id.tv_birthday);

		radioGender = (RadioGroup) findViewById(R.id.gender_group);
		radioMale = (RadioButton) findViewById(R.id.rd_male);
		radioFamale = (RadioButton) findViewById(R.id.rd_female);
		loading = findViewById(R.id.loadingPanel);

		btnUpdate = (Button) findViewById(R.id.btn_update);
	}

	public void btnClicked(View v) {
		switch (v.getId()) {
		case R.id.btn_update:
			if (btnUpdate.getText().equals(getString(R.string.edit))) {		// click to edit
				// edit
				setEditInfo(true);
				btnUpdate.setText(getString(R.string.update));
				
				btnUpdate.setText(getString(R.string.update));
				tvUserName.setText(edtUserName.getText().toString());
				tvPhone.setText(edtPhone.getText().toString());
				tvEmail.setText(edtEmail.getText().toString());
				tvAddress.setText(edtAddress.getText().toString());
				tvBirthday.setText(edtBirthday.getText().toString());
				
				
				edtUserName.requestFocus();
			} else {	// click to save
				setEditInfo(false);
				btnUpdate.setText(getString(R.string.edit));
				
				updateUser(true);
			}
			break;
		default:
			break;
		}
	}

	private void setEditInfo(boolean isEdit) {
		int visibility = isEdit ? View.VISIBLE : View.GONE;
		int unVisibility = isEdit ? View.GONE : View.VISIBLE;

		edtUserName.setVisibility(visibility);
		edtPhone.setVisibility(visibility);
		edtEmail.setVisibility(visibility);
		edtBirthday.setVisibility(visibility);
		edtAddress.setVisibility(visibility);

		tvUserName.setVisibility(unVisibility);
		tvPhone.setVisibility(unVisibility);
		tvEmail.setVisibility(unVisibility);
		tvBirthday.setVisibility(unVisibility);
		tvAddress.setVisibility(unVisibility);

		if (visibility == View.VISIBLE) {
			radioFamale.setVisibility(visibility);
			radioMale.setVisibility(visibility);
		} else {
			if (radioFamale.isChecked()) {
				radioFamale.setVisibility(View.VISIBLE);
				radioMale.setVisibility(View.GONE);
			} else {
				radioFamale.setVisibility(View.GONE);
				radioMale.setVisibility(View.VISIBLE);
			}
		}
	}

	public void updateUser(boolean showAlert) {
		String userName = edtUserName.getText().toString().trim();
		String phone = edtPhone.getText().toString().trim();
		String email = edtEmail.getText().toString().trim();
		String address = edtAddress.getText().toString().trim();
		String birthday = edtBirthday.getText().toString().trim();
		String gender = radioFamale.isChecked() ? "Male" : "Female";
		String id = new BooPreference(this).getPref().getString(
				BooPreference.KEY_USER_ID, "");
		if (isAutoRegistering) {
			return;
		}
		if (id.equals("")) {
			loading.setVisibility(View.VISIBLE);
			new AccountService(this).autoRegister();
			isAutoRegistering = true;
			return;
		} else {
			isAutoRegistering = false;
		}
		if (userName == null || phone == null || email == null
				|| address == null || birthday == null || gender == null
				|| userName.equals("") || phone.equals("") || email.equals("")
				|| address.equals("") || birthday.equals("")
				|| gender.equals("")) {
			if (showAlert) {
				// show dialog confirm
				Builder build = new Builder(this).setCancelable(true)
						.setTitle("Request Info")
						.setMessage("All fields must not empty.")
						.setNegativeButton("OK", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				build.create().show();
			}
			return;
		}
		loading.setVisibility(View.VISIBLE);
		sendUpdateData(id, userName, email, phone, birthday,gender, address);
	}

	
	
	public boolean chechValidate(ObjUser user){
		if(!isString(user.getCustName())|| !isString(user.getCustPhone())|| !isString( user.getCustEmail()) || !isString(user.getCustAddress())
				|| !isString(user.getBirthday()) || !isString(user.getGender())){
			
			showAlert("Nhập thông tin", "bạn phải nhập đầy đủ thông tin!");
			return false;
		}
		return true;
	}
	public  boolean isString(String value) {

		if (value == null || value.length() == 0 || value == "") {
			return false;
		}

		return true;
	}


	public void sendUpdateData(String id, String name, String email, String phone,String birthday,  String gender,String address){
		try {
			SendDataService service = new SendDataService(this);
			JsonHttpResponseHandler callBack = new JsonHttpResponseHandler(){
				@Override
				public void onSuccess(JSONObject response) {
					 successRegister(response);
				}
				@Override
				public void onFailure(Throwable error) {
					errorRegis();
				}
			};
			JSONObject jsonParams = new JSONObject();
			jsonParams.put("custId", id);
			jsonParams.put("custName", name);
			jsonParams.put("custPhone", phone);
			jsonParams.put("custEmail",email);
			jsonParams.put("custAddress",address);
			jsonParams.put("birthday",birthday);
			if(gender.equals("Male")){
				jsonParams.put("gender", 0);
			}
			else{
				jsonParams.put("gender", 1);
			}
			
			service.getData(Constant.API_UPDATE_USER_INFO, jsonParams, callBack);
		}
		catch (Exception e){
			errorRegis();
		}
	}
	
	public void  successRegister(JSONObject object){
		try {
			JSONObject result = object.getJSONObject("Result");
			String userStr = result.toString();
			Gson gson = new Gson();
			HomeActivity.userInfo = gson.fromJson(userStr, ObjUser.class);
			showAlert("Thông báo", "Bạn đã đăng kí thông tin thành công với hệ thống Boo!");
			loading.setVisibility(View.GONE);
			
			refreshDataContext();
		}
		catch (Exception e)
		{
			errorRegis();
		}	
		
	}
	public void errorRegis(){
		loading.setVisibility(View.GONE);
		showAlert("Error", "Đã có lỗi khi kết nối đến server. Xin vui lòng thử lại!");
	}
	public void showAlert(String title, String message){
		Builder build = new Builder(UpdateInfoActivity.this).setCancelable(true)
				.setTitle(title)
				.setMessage(message)
				.setNegativeButton("Close", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		build.create().show();
	}
	private void refreshDataContext(){
		if (HomeActivity.userInfo!=null) {
			ObjUser currentUser = HomeActivity.userInfo;
			edtUserName.setText(currentUser.getCustName());
			edtPhone.setText(currentUser.getCustPhone());
			edtEmail.setText(currentUser.getCustEmail());
			edtAddress.setText(currentUser.getCustAddress());
			edtBirthday.setText(currentUser.getBirthday());

			tvUserName.setText(currentUser.getCustName());
			tvPhone.setText(currentUser.getCustPhone());
			tvEmail.setText(currentUser.getCustEmail());
			tvAddress.setText(currentUser.getCustAddress());
			tvBirthday.setText(currentUser.getBirthday());

			String gender = currentUser.getGender();
			if ("male".compareToIgnoreCase(gender + "") == 0) {
				radioFamale.setChecked(true);
				radioFamale.setVisibility(View.VISIBLE);
			} else {
				radioFamale.setChecked(true);
				radioFamale.setVisibility(View.VISIBLE);
			}
		}
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			final Calendar c = Calendar.getInstance();
			int mYear = c.get(Calendar.YEAR);
			int mMonth = c.get(Calendar.MONTH);
			int mDay = c.get(Calendar.DAY_OF_MONTH);
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}
}
